import random
import string
from flask import Blueprint, render_template, request, jsonify, redirect, url_for,session
from exts import mail,db
from flask_mail import Message
from models.email_captcha_model import EmailCaptchaModel
from models.user_model import UserModel
from .forms import RegisterForm, LoginForm
from werkzeug.security import generate_password_hash,check_password_hash

bp = Blueprint('auth', __name__, url_prefix='/auth')

@bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'GET':
        return render_template("login.html")
    else:
        form = LoginForm(request.form)
        if form.validate():
            email = form.email.data
            password = form.password.data
            user = UserModel.query.filter_by(email=email).first()
            if not user:
                return redirect(url_for('auth.login'))
            if check_password_hash(user.password, password):
                # cookie
                # 一般用来存放登录授权的东西
                # flask 中的 session是经过加密后存储到 cookie中的
                session['user_id'] = user.id
                return redirect("/")
            else:
                print("password error")
                return redirect(url_for('auth.login'))
        else:
            return redirect(url_for('auth.login'))

@bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'GET':
        return render_template("register.html")
    else:
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            username = form.username.data
            password = form.password.data

            user = UserModel(email=email, username=username,password=generate_password_hash(password,method='pbkdf2:sha256'))
            db.session.add(user)
            db.session.commit()
            # return redirect("/auth/login")
            return redirect(url_for("auth.login"))
        else:
            print(form.errors)
            return redirect(url_for("auth.register"))


@bp.route('/mail/captcha', methods=['GET'])
def get_captcha():
    email = request.args.get('email')
    if not email:
        return "Error"
    source = string.digits * 4
    captcha = random.sample(source, 4)
    captcha = "".join(captcha)
    message = Message(subject="Leslie Web captcha", recipients=[email], body=f"Your email captcha is: {captcha}")
    mail.send(message)
    # store captcha to database
    email_captcha = EmailCaptchaModel(email=email,captcha=captcha)
    print(email_captcha)
    db.session.add(email_captcha)
    db.session.commit()
    # memcached / redis / db
    return jsonify({"code":200, "message":"", "data": ""})


@bp.route('/mail/test', methods=['GET'])
def test_mail():
    message = Message(subject="test sina mail", recipients=["su_zhen1943@sina.com"],body="test mail body")
    mail.send(message)
    return "Email sent"

@bp.route("/logout")
def logout():
    session.clear()
    return redirect(url_for("auth.login"))